/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 */
package com.sunyard.client2.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * @Description:
 * 
 * @author <a href="mailto:jh200326630615@163.com">Watermud</a>
 * @version 1.0
 * @date 2010-3-25
 */

public class PropertiesUtil {

	/**
	 * remove this field, don't use this in multy threads app
	 */
	@Deprecated
	private static Properties pro;

	/**
	 * remove this methos ,replaced by <code>loadConfigsR(String[])</code>
	 * 
	 * @param file
	 */
	@Deprecated
	public static Properties loadConfigs(String[] file) {
		if (pro == null) {
			pro = new Properties();
		} else {
			pro.clear();
		}
		InputStream is = null;
		for (int i = 0; i < file.length; i++) {
			try {
				is = new FileInputStream(file[i]);
				pro.load(is);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				return null;
			} catch (IOException e) {
				e.printStackTrace();
				return null;
			} finally {
				if (is != null) {
					try {
						is.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		dealProperties(pro);
		return pro;
	}

	/**
	 * remove this methos ,replaced by <code>loadConfigR(String)</code>
	 * 
	 * @param file
	 */
	@Deprecated
	public static Properties loadConfig(String file) {
		if (pro == null) {
			pro = new Properties();
		} else {
			pro.clear();
		}
		InputStream is = null;
		try {
			is = new FileInputStream(file);
			pro.load(is);
			dealProperties(pro);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return pro;
	}

	public static Properties loadConfigsR(String[] file)
			throws FileNotFoundException, IOException {
		Properties pro = new Properties();
		InputStream is = null;
		for (int i = 0; i < file.length; i++) {
			try {
				is = new FileInputStream(file[i]);
				pro.load(is);
			} finally {
				if (is != null) {
					try {
						is.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		dealProperties(pro);
		return pro;
	}

	/**
	 * 网络环境，从
	 * @param file
	 * @return
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public static Properties loadConfigR(String file)
			throws FileNotFoundException, IOException {
		Properties pro = new Properties();
		InputStream is = null;
		try {
		    is = new FileInputStream(file);

			pro.load(is);
			dealProperties(pro);
			return pro;
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	// public static Properties loadConfigFromUserPath(String file)
	// throws FileNotFoundException, IOException {
	// Properties pro = new Properties();
	// InputStream is = null;
	// try {
	// is = new FileInputStream(file);
	// // is = ConfigFileUtil.getConfigStream(file);
	// pro.load(is);
	// dealProperties(pro);
	// return pro;
	// } finally {
	// if (is != null) {
	// try {
	// is.close();
	// } catch (IOException e) {
	// e.printStackTrace();
	// }
	// }
	// }
	// }

	public static Properties loadConfigStream(InputStream is)
			throws IOException {
		Properties pro = new Properties();
		try {
			pro.load(is);
			dealProperties(pro);
			return pro;
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 处理Properties类中的值，去掉前后的空格，将none转换成空字符串。
	 * 
	 * @param pro2
	 */
	private static void dealProperties(Properties pro2) {
		Set keys = pro2.keySet();
		for (Iterator iterator = keys.iterator(); iterator.hasNext();) {
			String key = (String) iterator.next();
			String value = (String) pro2.get(key);
			if (value.toLowerCase().intern() == "none") {
				pro2.put(key, "");
			} else {
				pro2.put(key, value.trim());
			}
		}
	}

	@Deprecated
	public static String getValue(String key) {
		if (pro == null) {
			System.out.println("please load config file first!");
			return null;
		}
		return pro.getProperty(key);
	}

	/**
	 * 将map中的配置添加到配置文件
	 * 
	 * @param file
	 * @param map
	 */
	public static void writeToFile(File file, Map map) {
		try {
			BufferedReader reader = new BufferedReader(new FileReader(file));
			File temp = new File(file.getParentFile(), "temp.properties");
			FileWriter writer = new FileWriter(temp);
			String line = "";
			String key;
			Set keys = map.keySet();
			while ((line = reader.readLine()) != null) {
				int i = line.indexOf("=");
				if (i > 0) {
					key = line.substring(0, i).trim();
					// FIXME 需要处理注释，保留注释
					if (keys.contains(key)) {
						writer.write(key
								+ " = "
								+ (String) map
										.get(key)
								+ System.getProperty("line.separator"));
						map.remove(key);
						continue;
					}
				}
				writer.write(line + System.getProperty("line.separator"));
			}
			writer.write(System.getProperty("line.separator"));
			keys = map.keySet();
			for (Iterator iterator = keys.iterator(); iterator.hasNext();) {
				key = (String) iterator.next();
				writer.write(key + " = "
						+ (String) map.get(key)
						+ System.getProperty("line.separator"));
			}
			writer.close();
			reader.close();
			file.delete();
			if (file.exists()) {
				return;
			}
			temp.renameTo(file);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 配置添加到配置文件
	 * 
	 * @param file
	 * @param key
	 * @param value
	 * @return
	 */
	public static boolean writeToFile(File file, String key, String value) {
		try {
			BufferedReader reader = new BufferedReader(new FileReader(file));
			File temp = new File(file.getParentFile(), "temp.properties");
			FileWriter writer = new FileWriter(temp);
			String line = "";
			boolean finded = false;
			while ((line = reader.readLine()) != null) {
				if (line.trim().startsWith(key.trim())) {// FIXME 需要处理注释，保留注释
					writer.write(key + " = " + value
							+ System.getProperty("line.separator"));
					finded = true;
					break;
				} else {
					writer.write(line + System.getProperty("line.separator"));
				}
			}
			if (!finded) {
				writer.write(key + " = " + value
						+ System.getProperty("line.separator"));
			}
			writer.close();
			reader.close();
			file.delete();
			if (file.exists()) {
				return false;
			}
			temp.renameTo(file);
			return true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}

}
